import axios from 'axios';
import { getToken, removeToken } from './auth';
export const BASE_URL = 'http://localhost:8080';

const API = axios.create({
  baseURL: BASE_URL
});

// 请求拦截器
API.interceptors.request.use(config => {
  const { url } = config; 
  if (url.startsWith('/user') && !url.startsWith('/user/login') && !url.startsWith('/user/registered')) {
    // 添加请求头
    config.headers.Authorization = getToken();
  }
  return config;
});

// 响应拦截器
API.interceptors.response.use(response => {
  const { status } = response.data
  if (status === 400) removeToken(); // Token失效
  return response;
});

export { API };